package pkg

import (
	"errors"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
)

type TelemetryConfig struct {
	Name     string
	Endpoint string
	Bathcer  string
}

func NewTracerProvider(telemetryConfig TelemetryConfig) (*trace.TracerProvider, error) {
	if telemetryConfig.Bathcer != "jaeger" {
		return nil, errors.New("Implement other link trackers themselves")
	}

	// 配置
	exporter, err := jaeger.New(
		jaeger.WithCollectorEndpoint(
			jaeger.WithEndpoint(telemetryConfig.Endpoint),
		),
	)
	if err != nil {
		return nil, err
	}
	tp := trace.NewTracerProvider(
		trace.WithBatcher(exporter),
		trace.WithResource(
			// 设置全局属性，应用级别.对应显示在 process
			resource.NewWithAttributes(
				semconv.SchemaURL, // 固定写发，最好使用最新版本下的
				semconv.ServiceNameKey.String(telemetryConfig.Name), // jaeger 界面上的 Service
				//attribute.String("env", "dev"),        // 设置环境，实际开发中有不同环境
			),
		),
	)

	otel.SetTracerProvider(tp)

	// *创建传播器, 设置全局（本案例重点部分）
	otel.SetTextMapPropagator(
		propagation.NewCompositeTextMapPropagator(
			propagation.TraceContext{},
			propagation.Baggage{}, // 包裹方式
		),
	)

	return tp, nil
}
